<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { useAuthStore } from '@/store/modules/auth';
import { useAuth } from '@/hooks/business/auth';
import { useButtonPermission } from '@/utils/button';
import { $t } from '@/locales';

defineOptions({
  name: 'ToggleAuth'
});

const authStore = useAuthStore();
const { hasAuthSync } = useAuth();
const { hasPermissionSync, getUserPermissions: getButtonPermissions } = useButtonPermission();

const loading = ref(false);
const loginAccount = ref('');

const accounts = [
  { key: 'admin', label: 'Admin', roles: ['R_ADMIN'], buttons: ['B_CODE2', 'USER_ADD', 'USER_EDIT'] },
  {
    key: 'super',
    label: 'Super Admin',
    roles: ['R_SUPER'],
    buttons: ['B_CODE1', 'B_CODE2', 'USER_ADD', 'USER_EDIT', 'USER_DELETE']
  },
  { key: 'user', label: 'User', roles: ['R_USER'], buttons: ['B_CODE3'] },
  {
    key: 'multi',
    label: 'Multi Role User',
    roles: ['R_ADMIN', 'R_USER'],
    buttons: ['B_CODE2', 'B_CODE3', 'USER_ADD', 'USER_EDIT']
  }
];

const userButtonPermissions = ref<string[]>([]);
const asyncButtonPermissions = ref<string[]>([]);

async function handleToggleAccount(account: (typeof accounts)[0]) {
  loading.value = true;
  loginAccount.value = account.key;

  try {
    // 模拟登录过程
    await new Promise<void>(resolve => {
      setTimeout(() => resolve(), 1000);
    });

    // 更新用户信息
    authStore.userInfo.roles = account.roles;
    authStore.userInfo.buttons = account.buttons;

    // 获取按钮权限（同步版本）
    userButtonPermissions.value = authStore.userInfo.buttons;

    // 获取按钮权限（异步版本，多角色并集）
    asyncButtonPermissions.value = await getButtonPermissions();

    console.log('账户切换完成:', {
      account: account.key,
      roles: account.roles,
      buttons: account.buttons,
      asyncPermissions: asyncButtonPermissions.value
    });

    window.$message?.success(`已切换到 ${account.label} 账户`);
  } catch (error) {
    console.error('账户切换失败:', error);
    window.$message?.error('账户切换失败');
  } finally {
    loading.value = false;
  }
}

async function refreshPermissions() {
  try {
    // 清除缓存并重新获取权限
    const permissions = await getButtonPermissions();
    asyncButtonPermissions.value = permissions;
    console.log('权限刷新完成:', permissions);
    window.$message?.success('权限已刷新');
  } catch (error) {
    console.error('权限刷新失败:', error);
    window.$message?.error('权限刷新失败');
  }
}

onMounted(() => {
  // 初始化时获取当前用户的按钮权限
  userButtonPermissions.value = authStore.userInfo.buttons;
  getButtonPermissions().then(permissions => {
    asyncButtonPermissions.value = permissions;
  });
});
</script>

<template>
  <ASpace direction="vertical" :size="16">
    <ACard :title="$t('route.function_toggle-auth')" :bordered="false" size="small" class="card-wrapper">
      <ADescriptions layout="vertical" bordered size="small" :column="1">
        <ADescriptionsItem :label="$t('page.manage.user.userRole')">
          <ASpace>
            <ATag v-for="role in authStore.userInfo.roles" :key="role" color="blue">{{ role }}</ATag>
          </ASpace>
        </ADescriptionsItem>
        <ADescriptionsItem :label="$t('page.function.toggleAuth.toggleAccount')">
          <ASpace>
            <AButton
              v-for="account in accounts"
              :key="account.key"
              :loading="loading && loginAccount === account.key"
              :disabled="loading && loginAccount !== account.key"
              @click="handleToggleAccount(account)"
            >
              {{ account.label }}
            </AButton>
          </ASpace>
        </ADescriptionsItem>
        <ADescriptionsItem label="当前用户按钮权限（同步版本）">
          <ASpace wrap>
            <ATag v-for="button in userButtonPermissions" :key="button" color="green">{{ button }}</ATag>
            <span v-if="userButtonPermissions.length === 0" class="text-gray-400">无权限</span>
          </ASpace>
        </ADescriptionsItem>
        <ADescriptionsItem label="当前用户按钮权限（异步版本，多角色并集）">
          <ASpace wrap>
            <ATag v-for="button in asyncButtonPermissions" :key="button" color="orange">{{ button }}</ATag>
            <span v-if="asyncButtonPermissions.length === 0" class="text-gray-400">无权限</span>
          </ASpace>
          <AButton size="small" class="mt-8px" @click="refreshPermissions">刷新权限</AButton>
        </ADescriptionsItem>
      </ADescriptions>
    </ACard>

    <ACard title="按钮权限测试" :bordered="false" size="small" class="card-wrapper">
      <ADescriptions layout="vertical" bordered size="small" :column="1">
        <ADescriptionsItem label="权限检查结果（同步版本）">
          <ASpace>
            <AButton v-if="hasAuthSync('B_CODE1')" type="primary">超级管理员可见按钮 (B_CODE1)</AButton>
            <AButton v-if="hasAuthSync('B_CODE2')" type="primary">管理员可见按钮 (B_CODE2)</AButton>
            <AButton v-if="hasAuthSync('B_CODE3')" type="primary">管理员或用户可见按钮 (B_CODE3)</AButton>
            <AButton v-if="hasAuthSync('USER_ADD')" type="primary">新增用户 (USER_ADD)</AButton>
            <AButton v-if="hasAuthSync('USER_EDIT')" type="primary">编辑用户 (USER_EDIT)</AButton>
            <AButton v-if="hasAuthSync('USER_DELETE')" type="primary">删除用户 (USER_DELETE)</AButton>
            <span
              v-if="!hasAuthSync(['B_CODE1', 'B_CODE2', 'B_CODE3', 'USER_ADD', 'USER_EDIT', 'USER_DELETE'])"
              class="text-gray-400"
            >
              无任何按钮权限
            </span>
          </ASpace>
        </ADescriptionsItem>
        <ADescriptionsItem label="权限检查结果（异步版本，多角色并集）">
          <ASpace>
            <AButton v-if="hasPermissionSync('B_CODE1')" type="primary" ghost>超级管理员可见按钮 (B_CODE1)</AButton>
            <AButton v-if="hasPermissionSync('B_CODE2')" type="primary" ghost>管理员可见按钮 (B_CODE2)</AButton>
            <AButton v-if="hasPermissionSync('B_CODE3')" type="primary" ghost>管理员或用户可见按钮 (B_CODE3)</AButton>
            <AButton v-if="hasPermissionSync('USER_ADD')" type="primary" ghost>新增用户 (USER_ADD)</AButton>
            <AButton v-if="hasPermissionSync('USER_EDIT')" type="primary" ghost>编辑用户 (USER_EDIT)</AButton>
            <AButton v-if="hasPermissionSync('USER_DELETE')" type="primary" ghost>删除用户 (USER_DELETE)</AButton>
            <span
              v-if="!hasPermissionSync(['B_CODE1', 'B_CODE2', 'B_CODE3', 'USER_ADD', 'USER_EDIT', 'USER_DELETE'])"
              class="text-gray-400"
            >
              无任何按钮权限
            </span>
          </ASpace>
        </ADescriptionsItem>
      </ADescriptions>
    </ACard>

    <ACard title="说明" :bordered="false" size="small" class="card-wrapper">
      <div class="text-sm text-gray-600">
        <p>
          <strong>同步版本：</strong>
          直接使用 authStore 中的 buttons 数组，只包含单个角色的权限
        </p>
        <p>
          <strong>异步版本：</strong>
          通过API获取所有角色的按钮权限并做并集处理，支持多角色权限合并
        </p>
        <p>
          <strong>多角色用户：</strong>
          选择 "Multi Role User" 可以看到多角色权限并集的效果
        </p>
        <p>
          <strong>权限刷新：</strong>
          点击"刷新权限"按钮可以清除缓存并重新获取权限
        </p>
      </div>
    </ACard>
  </ASpace>
</template>

<style scoped></style>
